package com.cn.demo.service.impl;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class HeartbeatMarkerService {

    private final ValueOperations<String, Long> valueOps;
    private static final String COUNTER_KEY = "hert_rap_counter";
    private static final String COUNTER_MARK_KEY = "hert_rap_counter:mark";

    public HeartbeatMarkerService(@Qualifier("longRedisTemplate") RedisTemplate<String, Long> redisTemplate) {
        this.valueOps = redisTemplate.opsForValue();
    }

    /**
     * 每分钟记录心跳计数器标记
     */
    @Scheduled(fixedRate = 1, timeUnit = TimeUnit.MINUTES)
    public void markHeartbeatCounter() {

        // 记录当前时间点的心跳数
        Long currentCount = valueOps.get(COUNTER_KEY);
        if (currentCount != null) {
            valueOps.set(COUNTER_MARK_KEY, currentCount, 2, TimeUnit.MINUTES);
        }
    }

    /**
     * 获取最近一分钟心跳数
     */
    public long getRecentHeartbeatCount() {
        Long current = valueOps.get(COUNTER_KEY);
        Long lastMark = valueOps.get(COUNTER_MARK_KEY);

        if (current == null) return 0;
        if (lastMark == null) return current;

        return current - lastMark;
    }
}
